//
//  OrderPaymentController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/21.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "OrderPaymentController.h"
#import "OrderPaymentCell.h"
#import "AliPayOrder.h"
#import "WXApi.h"
#import "WXApiRequestHandler.h"
#import "OrderSuccessViewController.h"
#import "CreatStochasticOrderNumber.h"
#import "BaseNavigationController.h"

@interface OrderPaymentController ()<WXApiDelegate>

{
    NSInteger PayType;
    MBProgressHUD *progressHUD;
}

@property(nonatomic,strong)NSMutableArray *boolArray;

@property (nonatomic,strong)NSDictionary *userInfoDict;

@end

@implementation OrderPaymentController

- (NSMutableArray *)boolArray
{
    if (!_boolArray) {
        _boolArray = [NSMutableArray arrayWithObjects:@"0",@"1",@"0",@"0", @"0", nil];
    }
    return _boolArray;
}

- (NSDictionary *)userInfoDict {
    if (!_userInfoDict) {
        _userInfoDict = [NSDictionary dictionary];
    }
    return _userInfoDict;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadUserInfoNumberData];
    
    self.tableView.scrollEnabled = false;
    self.title = @"订单支付";
    PayType = 1;
    [self orderCreatCountMoney];
    NSLog(@"%@",self.judgeString);
    
    
    NSLog(@"%d",self.judgeOilRecharge);
    NSLog(@"%d",self.judgeRecharge);
    
    NSLog(@"%@",[[UIDevice currentDevice] systemVersion]);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processOrderWithPaymentResult:) name:@"processOrderWithPaymentResult" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processOrderWithWXOnRespPaymentResult:) name:@"processOrderWithWXOnRespPaymentResult" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(judgeWeChatBackType:) name:@"WeChatType" object:nil];
}

- (void)orderCreatCountMoney {
    if ([self.orderType isEqualToString:@"3"]) {
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME,@"order_ids":self.OrderString} AndMenthodName:@"/api/Cart/countMoney" completeBlock:^(id object) {
            NSLog(@"%@",object);
        }];
    }
}

- (void)loadUserInfoNumberData {
    
    NSDictionary *params = @{
                             @"username":USERNAME
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"api/User/info" completeBlock:^(id object) {
        self.userInfoDict = object[@"data"];
        [self.tableView reloadData];
    }];
}

- (void)rechargeBtnDidClick{
    
    if(PayType == 1) {
        NSLog(@"现金")
    } else if (PayType == 2) {
        NSLog(@"积分");
    } else if (PayType == 4) {
        NSLog(@"微信");
    } else  {
        NSLog(@"支付宝");
    }
    
    if (PayType == 3 || PayType == 4) {
        [self didClickAliOrWeChat];
    }
    
    if (PayType == 1 || PayType == 2) {
        
        if (PayType == 2) {
            if (self.judgeString.length) {
                return;
            }
        }
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"message:@"请输入二级密码"preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            
            textField.placeholder = @"输入密码";
            
            textField.secureTextEntry = YES;
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UITextField *password = alertController.textFields.lastObject;
        
            if ([self.orderType isEqualToString:@"1"]) {
                [self cartOrderWithRecharge:password.text];
            } else if ([self.orderType isEqualToString:@"2"]) {
                [self cartOrderWithOilCard:password.text];
            } else {
                [self creatOrderWithShop:password.text];
            }
        
        }];
        
        [alertController addAction:cancelAction];
        
        [alertController addAction:okAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark>>>>>>>> 支付宝和微信支付
- (void)didClickAliOrWeChat {

    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"oid":self.OrderString,
                             @"pay_type":[NSString stringWithFormat:@"%ld",PayType]
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/updateOrderPayType" completeBlock:^(id object) {
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            if (PayType == 4) {
                // 微信
#warning 实际金额要在此处填写时 * 100；
                //        NSString *price = [NSString stringWithFormat:@"%f",self.OrderMonryString.floatValue * 100];
                
                float priceFloat = self.OrderMonryString.floatValue * 100;
                int a = (int)priceFloat;
                NSString *price = [NSString stringWithFormat:@"%d",a];
                [WXApiRequestHandler jumpToWxPayWithOrderNumber:self.OrderString andOrderBodyString:self.OrderTitleString OrderPriceString:price andView:self.view];
            } else {
                
                
                // 支付宝
                //                [AliPayOrder doAlipayPayWithOrderNumber:self.OrderString andOrderAllPrice:self.OrderMonryString andOrderBodyTitle:self.OrderDescribeInfo andOrderSubject:self.OrderTitleString andBackDataBlock:^(id object) {
                //                    NSLog(@"%@",object);
                //
                //                    if ([object[@"resultStatus"] isEqualToString:@"9000"]) {
                //                        NSString *aliPayString = [object objectForKey:@"result"];
                //                        NSDictionary *dict = [self dictionaryWithJsonString:aliPayString];
                //                        OrderSuccessViewController *orderSuccess = [[OrderSuccessViewController alloc] init];
                //                        orderSuccess.orderNumber = self.OrderString;
                //                        orderSuccess.creatOrderTime = [dict[@"alipay_trade_app_pay_response"] objectForKey:@"timestamp"];;
                //                        orderSuccess.orderType = self.orderType;
                //                        [self.navigationController pushForm:self.navigationController pushToAndHidden:orderSuccess];
                //
                //                    } else {
                //
                //                        NSString *string = [object objectForKey:@"memo"];
                //
                //                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //                            if (string.length) {
                //                                MBProgressHUD *hud = [MBProgressHUD showMessage:object[@"memo"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                //                                [self.view addSubview:hud];
                //                            } else {
                //                                MBProgressHUD *hud = [MBProgressHUD showMessage:@"您尚未支付成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                //                                [self.view addSubview:hud];
                //                            }
                //                            
                //                        });
                //                    }
                //                    
                //                } andMBPView:self.view];
            }
            
        } else {
            NSString *message = [object[@"message"] objectForKey:@"view"];
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:message toView:self.view dimBackground:NO AndCompleteBlock:nil];
            
            [self.view addSubview:hud];
        }
        
    }];
    
}
#pragma mark>>>>>>>> 现金和积分支付

- (void)cartOrderWithRecharge:(NSString *)pwdtwoString {

    NSLog(@"话费");
    
    NSDictionary *params = @{
                             @"order_id":self.OrderString,
                             @"pay_type":[NSString stringWithFormat:@"%ld",PayType],
                             @"pass_safe":pwdtwoString
                             };
    
    NSLog(@"%@",params);
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict: params AndMenthodName:@"/api/Recharge/mobile" completeBlock:^(id object) {
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"话费充值成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                
                [self WeChatPushTuOrderSuccess];
            }];
            
            [self.view addSubview:hud];
            
        } else {
            NSString *message = [object[@"message"] objectForKey:@"view"];
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:message toView:self.view dimBackground:NO AndCompleteBlock:nil];
            
            [self.view addSubview:hud];
        }
    }];
    
}

- (void)cartOrderWithOilCard:(NSString *)pwdtwoString {

    NSLog(@"油卡");
    
    NSDictionary *params = @{
                             @"order_id":self.OrderString,
                             @"pay_type":[NSString stringWithFormat:@"%ld",PayType],
                             @"pass_safe":pwdtwoString
                             };
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Recharge/gasCard" completeBlock:^(id object) {
        NSLog(@"%@",object);
        
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"油卡充值成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                [self WeChatPushTuOrderSuccess];
            }];
            
            [self.view addSubview:hud];
            
        } else {
            NSString *message = [object[@"message"] objectForKey:@"view"];
            MBProgressHUD *hud = [MBProgressHUD showMessage:message toView:self.view dimBackground:NO AndCompleteBlock:nil];
            
            [self.view addSubview:hud];
        }
        
    }];
    
}

- (void)creatOrderWithShop:(NSString *)pwdString {
    
    NSDictionary *dict = @{
                           @"username":USERNAME,
                           @"password":pwdString,
                           @"order_id":self.OrderString,
                           @"pay_type":[NSString stringWithFormat:@"%ld",PayType]
                           };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"/api/Pay/payShop" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"商城购物成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                [self WeChatPushTuOrderSuccess];
            }];
            
            [self.view addSubview:hud];
            
        } else {
            NSString *message = [object[@"message"] objectForKey:@"view"];
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:message toView:self.view dimBackground:NO AndCompleteBlock:nil];
            
            [self.view addSubview:hud];
        }
        
    }];
}

#pragma mark>>>>>>>> 微信返回状态处理

- (void)judgeWeChatBackType:(NSNotification *)backData {
    BaseResp *resp = backData.object;
    
    NSString *strMsg=[NSString stringWithFormat:@"errcode:%d",resp.errCode];
    NSString *strTitle;
    if ([resp isKindOfClass:[PayResp class]]) {
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle=[NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                [self WeChatPushTuOrderSuccess];
                return;
                break;
                
            case WXErrCodeCommon:
                strMsg = @"支付错误，请稍后再试";
                break;
                
            case WXErrCodeUserCancel:
                strMsg = @"尚未支付成功";
                break;
                
            case WXErrCodeSentFail:
                strMsg = @"发送失败，请稍后再试";
                break;
                
            case WXErrCodeAuthDeny:
                strMsg = @"授权失败，请稍后再试";
                break;
                
            default:
                strMsg = @"微信不支持";
                break;
        }
    
        MBProgressHUD *hud = [MBProgressHUD showMessage:strMsg toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
    }
}

- (void)processOrderWithWXOnRespPaymentResult:(NSNotification *)notifica {
    BaseResp *resp = notifica.object;
    
    if([resp isKindOfClass:[PayResp class]]){
        
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg;
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                [self WeChatPushTuOrderSuccess];
                return;
                break;
                
            case WXErrCodeCommon:
                strMsg = @"支付错误，请稍后再试";
                break;
                
            case WXErrCodeUserCancel:
                strMsg = @"尚未支付成功";
                break;
                
            case WXErrCodeSentFail:
                strMsg = @"发送失败，请稍后再试";
                break;
                
            case WXErrCodeAuthDeny:
                strMsg = @"授权失败，请稍后再试";
                break;
                
            default:
                strMsg = @"微信不支持";
                break;
        }
        
        if (resp.errCode == 0) {
#warning 微信返回接口逻辑
        }
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:strMsg toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        
    }
    
}

- (void)WeChatPushTuOrderSuccess {
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    OrderSuccessViewController *orderSuccess = [[OrderSuccessViewController alloc] init];
    orderSuccess.orderNumber = self.OrderString;
    orderSuccess.creatOrderTime = dateString;
    orderSuccess.orderType = self.orderType;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:orderSuccess];
    
}

#pragma mark>>>>>>>> 支付宝状态处理
- (void)processOrderWithPaymentResult:(NSNotification *)notifica {
    
    NSDictionary *dict = notifica.object;
    
    NSLog(@"%@",dict);
    
    NSString *aliPayString = [dict objectForKey:@"result"];
    
    if ([dict[@"resultStatus"] isEqualToString:@"9000"]) {
        
        NSDictionary *dict = [self dictionaryWithJsonString:aliPayString];
        
        OrderSuccessViewController *orderSuccess = [[OrderSuccessViewController alloc] init];
        orderSuccess.orderNumber = self.OrderString;
        orderSuccess.creatOrderTime = [dict[@"alipay_trade_app_pay_response"] objectForKey:@"timestamp"];;
        orderSuccess.orderType = self.orderType;
        
        [self.navigationController pushForm:self.navigationController pushToAndHidden:orderSuccess];
        
        NSLog(@"%@",[self dictionaryWithJsonString:aliPayString]);
    } else {
        
        NSString *string = [dict objectForKey:@"memo"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (string.length) {
                MBProgressHUD *hud = [MBProgressHUD showMessage:dict[@"memo"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            } else {
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"您尚未支付成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            }
            
        });
    }
}




- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json字典解析失败：%@",err);
        
        return nil;
    }
    
    return dic;
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"processOrderWithPaymentResult" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"processOrderWithWXOnRespPaymentResult" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WeChatType" object:nil];
}

- (UIView *)payViewSetupUI
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/5 + 20)];
    UIButton *rechargeBtn = [[UIButton alloc] init];
    rechargeBtn.tag = 999;
    [rechargeBtn setTitle:@"立即支付" forState:UIControlStateNormal];
    [view addSubview:rechargeBtn];
    rechargeBtn.layer.cornerRadius = 5;
    rechargeBtn.layer.masksToBounds = YES;
    rechargeBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [rechargeBtn setBackgroundColor:DEFAULT_COLOR];
    
    [rechargeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(WIDTH-30);
        make.centerY.equalTo(view.mas_centerY);
        make.left.equalTo(view.mas_left).offset(15);
        make.height.mas_equalTo(40);
    }];
    
    [rechargeBtn addTarget:self action:@selector(rechargeBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    return view;
}

#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else{
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier= @"OrderPaymentControllerCell";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = FONT(15);
        cell.detailTextLabel.font = FONT(15);
    }
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        cell.textLabel.text = @"订单号";
        cell.detailTextLabel.text = self.OrderString;
    }else if (indexPath.section == 0 && indexPath.row == 1) {
        cell.textLabel.text = @"订单金额";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",self.OrderMonryString];
    } else if (indexPath.section ==1 && indexPath.row == 0){
        cell.textLabel.text = @"支付方式";
    }else{
        
        static NSString *OrderPaymentCellID= @"OrderPaymentConCell";
        
        OrderPaymentCell *cell=[tableView dequeueReusableCellWithIdentifier:OrderPaymentCellID];
        
        if (cell==nil) {
            cell= [[[NSBundle mainBundle] loadNibNamed:@"OrderPaymentCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        
        if ([self.boolArray[indexPath.row] isEqualToString:@"1"]) {
            cell.selectImg.image = [UIImage imageNamed:@"shoujichongzhi_0"];
        } else {
            cell.selectImg.image = [UIImage imageNamed:@"shoujichongzhi_1"];
        }
        cell.selectIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"dingdanzhifu_%ld",indexPath.row]];
        
        NSArray *arr = @[@"充值账户",@"代金券",@"微信"];
        cell.payTittle.text = [NSString stringWithFormat:@"%@",arr[indexPath.row - 1]];
        
        if (self.judgeString.length) {
            if (indexPath.row == 2) {
                cell.payTittle.textColor = [UIColor lightGrayColor];
                UIView *view = [[UIView alloc] init];
                view.backgroundColor = [UIColor lightGrayColor];
                [cell.contentView addSubview:view];
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(cell.payTittle.mas_left).with.offset(-3);
                    make.width.mas_equalTo(cell.payTittle.width + 6);
                    make.centerY.equalTo(cell.payTittle.mas_centerY);
                    make.height.mas_equalTo(1);
                }];
                
                UILabel *detailLabel = [[UILabel alloc] init];
                detailLabel.text = @"* 该订单不支持此方式";
                detailLabel.textColor = [UIColor redColor];
                detailLabel.font = [UIFont systemFontOfSize:15];
                [cell.contentView addSubview:detailLabel];
                
                [detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.equalTo(cell.contentView.mas_right).offset(-8);
                    make.height.equalTo(cell.contentView.mas_height);
                }];
            }
        }
        
        return cell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return;
    }
    
    if (indexPath.row == 2 && self.judgeString.length) {
        return;
    }
    
    for (NSInteger i=0; i<self.boolArray.count; i++) {
        if (indexPath.row == i) {
            self.boolArray[i] = @"1";
        }else{
            self.boolArray[i] = @"0";
        }
    }
    PayType = indexPath.row;
    if (indexPath.row == 3) {
        PayType = 4;
    }
    [self.tableView reloadData];
    NSLog(@"%ld",indexPath.row);
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 7;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section ==0) {
        return 0.01;
    }else{
        return HEIGHT/5;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    return [self payViewSetupUI];
}

@end
